<?
class ccdsTools
{
    var $ccdSQL;
    var $config;
    var $smarty;

    private $file_types=array
        (
        "image" => array
            (
            "png",
            "gif",
            "jpg",
            "jpeg",
            "gif",
            "psd",
            "bmp",
            "tga"
            ),
        "script" => array
            (
            "pl",
            "cgi",
            "js"
            ),
        "html" => array
            (
            "html",
            "htm"
            ),
        "text" => array("txt"),
        "audio" => array
            (
            "mp3",
            "mp4",
            "wma",
            "wav",
            "ape"
            ),
        "word" => array
            (
            "doc",
            "rtf"
            ),
        "excel" => array
            (
            "xls",
            "docx",
            "csv",
            "xlt"
            ),
        "pdf" => array("pdf"),
        "archive" => array
            (
            "zip",
            "rar",
            "bz",
            "gz",
            "sit",
            "tar"
            ),
        "template" => array("tpl"),
        "config" => array("conf"),
        "php" => array
            (
            "php",
            "php4",
            "php5"
            )
        );

    public $file_icons=array
        (
        "folder" => 'folder.png',
        "image" => 'image.png',
        "script" => 'script.png',
        "html" => 'page_white.png',
        "text" => 'page_white_text.png',
        "audio" => 'sound.png',
        "word" => 'page_white_word.png',
        "excel" => 'page_white_excel.png',
        "pdf" => 'page_white.ong',
        "archive" => 'page_white_zip.png',
        "template" => 'script.png',
        "config" => 'page_white.png',
        "php" => 'page_white_php.png',
        "other" => 'page_white.png',
        "buffer" => 'page_white_paste.png'
        );
//*************************************************************************************************************************

    function __construct( )
    {
        $this->config=ccdsConfig::getInstance();
        $this->smarty=ccdsSmarty::getInstance();
        $this->ccdSQL=ccdSQL::getInstance();

        if ( $this->config->get( 'USE_FTP' ) )
        {
            require_once 'Net/FTP.php';
        }
    }
//*************************************************************************************************************************

    static function &getInstance( )
    {
        static $obj;

        if ( !$obj )
        {
            $obj=new ccdsTools();
        }
        return $obj;
    }
//*************************************************************************************************************************

    function debug( $msg ) {

    /*  to be removed soon */
    }

//*************************************************************************************************************************

    function init_session( $user )
    {

        $_SESSION['CMS']['user_id']=$user['user_id'];
        $_SESSION['CMS']['user_level']=$user['user_level'];
        $_SESSION['CMS']['user_interface_lang_id']=$user['user_interface_lang_id'];
        $_SESSION['CMS']['user_lang_id']=$user['user_interface_lang_id'];
        $_SESSION['CMS']['user_lang_code']=$user['lang_code'];

        $_SESSION['CMS']['user_flags']=array();
        $query="SELECT * FROM user_flags WHERE user_flag_user_id='" . $user['user_id'] . "'";
        $res=$this->ccdSQL->query( $query );

        while ( $flag=$this->ccdSQL->fetch_assoc( $res ) )
        {
            $_SESSION['CMS']['user_flags'][$user['user_flag_name']]=1;
        }
    }
//*************************************************************************************************************************

    function mkdir( $path )
    {
        if ( true == $this->config->get( 'USE_FTP' ) )
        {

            $ftp=new Net_FTP();
            $ftp->setHostname( MMCMS_FTP_HOST );
            $ftp->setPort( MMCMS_FTP_PORT );
            $ftp->connect();
            $ftp->setUsername( MMCMS_FTP_USER );
            $ftp->setPassword( MMCMS_FTP_PASS );
            $ftp->login( MMCMS_FTP_USER, MMCMS_FTP_PASS );
            $ftp->pwd();
            $ftp->mkdir( MMCMS_FTP_WEB_ROOT . MMCMS_MEDIA_DIR . $path );
            $ftp->chmod( MMCMS_FTP_WEB_ROOT . MMCMS_MEDIA_DIR . $path, $this->config->get( 'DIR_CHMOD' ) );
            $ftp->disconnect();
        }
        else
        {
            @mkdir( $path, $this->config->get( 'DIR_CHMOD' ) ); //(int) $this->config->get('DIR_CHMOD'));
        }
    }


//*************************************************************************************************************************

    function addTabManager( $parent_tab, $new_id, $title )
    {
        $objResponse=new ccdsResponse();

        $this->smarty->assign( "id", $new_id );
        $sHtml=$this->smarty->fetch( $this->config->get( 'TPL_DIR' ) . "content_layout.tpl" );

        $objResponse->clsTabManager->addPanel( $parent_tab, array
            (
            "id" => "tab_" . $new_id,
            "title" => $title,
            "content" => "<div id='tab_" . $new_id . "'>" . $sHtml . "</div>"
            ));

        $objResponse->clsTabManager->create( 'TabManagerContent_' . $new_id, array
            (
            "tabPanel" => "contentTabs_" . $new_id,
            "tabContent" => "contentTabsContent_" . $new_id,
            "cssClass" => 'contentTab'
            ));

        $objResponse->clsTabManager->on( 'destroy', $parent_tab, "tab_" . $new_id, "
					function() {
				  	xajax.ext.tabManager.destroy('TabManagerContent_" . $new_id . "');
	  			}
	  " );
        return $objResponse;
    }
//*************************************************************************************************************************

    function set_cookie_fix_domain( $Name, $Value='', $Expires=0, $Path='', $Domain='', $Secure=false, $HTTPOnly=false )
    {
        if ( !empty( $Domain ) )
        {
            // Fix the domain to accept domains with and without 'www.'.
            if ( strtolower( substr( $Domain, 0, 4 ) ) == 'www.' )
                $Domain=substr( $Domain, 4 );
            $Domain='.' . $Domain;

            // Remove port information.
            $Port=strpos( $Domain, ':' );

            if ( $Port !== false )
                $Domain=substr( $Domain, 0, $Port );
        }

        header( 'Set-Cookie: ' . rawurlencode( $Name ) . '=' . rawurlencode( $Value )
            . ( empty( $Expires ) ? '' : '; expires=' . gmdate( 'D, d-M-Y H:i:s', $Expires ) . ' GMT' )
            . ( empty( $Path ) ? '' : '; path=' . $Path ) . ( empty( $Domain ) ? '' : '; domain=' . $Domain )
            . ( !$Secure ? '' : '; secure' ) . ( !$HTTPOnly ? '' : '; HttpOnly' ),
            false );
    }

//*************************************************************************************************************************

    function getObjectElements( $obj_id, $language_id )
    {

        $query="SELECT obj_id,obj_key_class_id,obj_key_project_id FROM obj_index ";

        if ( !CMS_PREVIEW_MODE )
        {
            $query.=" 	STRAIGHT_JOIN obj_index_public ON (objp_key_obj_id=obj_id AND objp_key_lang_id=" . $language_id
                . ") ";
        }

        $query.=" WHERE obj_parent_obj_id = '" . $obj_id . "' AND obj_deleted=0 ORDER BY obj_position";
        $res=$this->ccdSQL->query( $query );
        $result=array();

        while ( $row=$this->ccdSQL->fetch_assoc( $res ) )
        {
            $foo=new ccdsObject( $row['obj_id'], $row['obj_key_class_id'], $row['obj_key_project_id'] );
            $obj=$foo->getObject( $language_id );

            if ( is_array( $obj ) )
                $result[]=$obj;
        }
        return $result;
    }

//*************************************************************************************************************************

    function getObjectElementlist( $obj_id, $language_id )
    {

        //	if (MEMCACHED_ENABLED) {
        //		$key = "getObjectElementlist".$obj_id."x".$language_id;
        //		if ($obj=$memcache->get($key)) {
        //			return $obj;
        //		}
        //	}

        $query="
							SELECT * FROM obj_index 
							STRAIGHT_JOIN obj_index_public ON 
							(objp_key_obj_id=obj_id AND objp_key_lang_id = '" . $language_id . "')							
							WHERE 
							obj_parent_obj_id = '" . $obj_id . "' AND obj_deleted=0
							AND obj_deleted=0
							AND (
								(obj_expire=0) 
									OR  (
										obj_expire=1 
										AND obj_expire_start <= '" . $_SERVER['REQUEST_TIME'] . "'
										AND obj_expire_end >= '" . $_SERVER['REQUEST_TIME'] . "'
									)
							)								
							ORDER BY obj_position
							";
        $res=$this->ccdSQL->query( $query );
        $result=array();

        while ( $row=$this->ccdSQL->fetch_assoc( $res ) )
        {
            $result[]=$row;
        }
        //	if (MEMCACHED_ENABLED)	$memcache->set($key, $result, false, MEMCACHED_EXPIRE);

        return $result;
    }

//*************************************************************************************************************************

    function getObjectClasses( $obj_id )
    {

        $query="SELECT * FROM obj_index WHERE obj_id='" . $obj_id . "'";
        $res=$this->ccdSQL->query( $query );
        $obj=$this->ccdSQL->fetch_assoc( $res );

        $classes=array();

        $query=
            "SELECT * FROM classes LEFT JOIN extensions ON class_key_ext_id = ext_id  WHERE ext_key_project_id='"
            . $obj['obj_key_project_id'] . "' order by class_name";
        $res=$this->ccdSQL->query( $query );
        $classes=array();

        while ( $row=$this->ccdSQL->fetch_assoc( $res ) )
        {
            $classes[]=$row;
        }

        return $classes;
    }
//*************************************************************************************************************************

    function getObjectDetails( $obj_id, $language_id, $display_contents=true )
    {

        $obj=new ccdsObject( $obj_id );
        return $obj->getObject( $language_id, $display_contents );
    }

    function getObjGroupPermissions( $obj_id, $group_id )
    {

        $permissions=array();

        $query="SELECT * FROM permissions_obj_index_2_group 
							WHERE 
								obj_index_2_group_key_obj_id='" . $obj_id . "' AND 
								obj_index_2_group_key_group_id='" . $group_id . "'
							";

        $res=$this->ccdSQL->query( $query );

        if ( !$row=$this->ccdSQL->fetch_assoc( $res ) )
        {
            $query="SELECT obj_parent_obj_id FROM obj_index WHERE obj_id='" . $obj_id . "'";
            $res=$this->ccdSQL->query( $query );
            $row=$this->ccdSQL->fetch_assoc( $res );

            if ( $row['obj_parent_obj_id'] != "0" )
                $permissions=$this->getObjGroupPermissions( $row['obj_parent_obj_id'], $group_id );
        }
        else
        {
            $permissions['read']=$row['obj_index_2_group_read'];
            $permissions['modify']=$row['obj_index_2_group_modify'];
            $permissions['delete']=$row['obj_index_2_group_delete'];
            $permissions['new']=$row['obj_index_2_group_new'];
        }

        return $permissions;
    }

// ************************************************************************************************************************

    function getObjUserPermissions( $obj_id, $group_id, $user_id )
    {

        $permissions=array();

        $query="SELECT * FROM permissions_obj_index_2_user
							WHERE 
								obj_index_2_user_key_obj_id='" . $obj_id . "' AND 
								obj_index_2_user_key_group_id='" . $group_id . "' AND
								obj_index_2_user_key_user_id='" . $user_id . "' 
							";

        $res=$this->ccdSQL->query( $query );

        if ( !$row=$this->ccdSQL->fetch_assoc( $res ) )
        {
            $query="SELECT obj_parent_obj_id FROM obj_index WHERE obj_id='" . $obj_id . "'";
            $res=$this->ccdSQL->query( $query );
            $row=$this->ccdSQL->fetch_assoc( $res );

            if ( $row['obj_parent_obj_id'] != "0" )
                $permissions=$this->getObjUserPermissions( $row['obj_parent_obj_id'], $group_id, $user_id );
        }
        else
        {
            $permissions['read']=$row['obj_index_2_user_read'];
            $permissions['modify']=$row['obj_index_2_user_modify'];
            $permissions['delete']=$row['obj_index_2_user_delete'];
            $permissions['new']=$row['obj_index_2_user_new'];
        }
        return $permissions;
    }
// ************************************************************************************************************************

    function getClassUserPermissions( $obj_id, $group_id, $user_id ) { }

    function PermissionsObj2UserGet( $user_id, $obj_id, $user_level )
    {
        if ( $user_level >= 1000 )
        {
            $result=array
                (
                "read" => 1,
                "modify" => 1,
                "new" => 1,
                "delete" => 1
                );
        }
        else
        {
            $result=array
                (
                "read" => 0,
                "modify" => 0,
                "new" => 0,
                "delete" => 0
                );

            $query=
                "SELECT * FROM permissions_obj_index_2_user WHERE obj_index_2_user_key_user_id='" . $user_id
                . "' AND obj_index_2_user_key_obj_id='" . $obj_id . "'";
            $res_p=$this->ccdSQL->query( $query );

            if ( $row=$this->ccdSQL->fetch_assoc( $res_p ) )
            {
                $result['read']=$row['obj_index_2_user_read'];
                $result['modify']=$row['obj_index_2_user_modify'];
                $result['delete']=$row['obj_index_2_user_delete'];
                $result['new']=$row['obj_index_2_user_new'];
            }
            else
            {
                $query="SELECT * FROM obj_index WHERE obj_id='" . $obj_id . "'";
                $res=$this->ccdSQL->query( $query );
                $row=$this->ccdSQL->fetch_assoc( $res );

                if ( $row['obj_parent_obj_id'] > 0 )
                {
                    $result=$this->PermissionsObj2UserGet( $user_id, $row['obj_parent_obj_id'], $user_level );
                }
                else
                {
                    $query="SELECT obj_key_project_id FROM obj_index WHERE obj_id='" . $obj_id . "'";
                    $res=$this->ccdSQL->query( $query );
                    $obj=$this->ccdSQL->fetch_assoc( $res );
                    $query=
                        " SELECT * FROM permissions_project_user WHERE project_user_key_project_id='"
                        . $obj['obj_key_project_id'] . "' AND project_user_key_user_id='" . $user_id . "'";
                    $res=$this->ccdSQL->query( $query );

                    if ( $row=$this->ccdSQL->fetch_assoc( $res ) )
                    {

                        $result['read']=$row['project_user_read'];
                        $result['modify']=$row['project_user_modify'];
                        $result['delete']=$row['project_user_delete'];
                        $result['new']=$row['project_user_new'];
                    }
                    else
                    {
                        $result['read']=0;
                        $result['modify']=0;
                        $result['delete']=0;
                        $result['new']=0;
                    }
                }
            }
        }
        return $result;
    }

    function getRecursivePath( $obj_id, $lang_id=false, $prefix=false )
    {

        $result=array();
        $entry=array();
        $query="SELECT * FROM obj_index WHERE obj_id = '" . $obj_id . "'";
        $res=$this->ccdSQL->query( $query );

        if ( $row=$this->ccdSQL->fetch_array( $res ) )
        {
            if ( !$lang_id )
            {
                $lang_id=$_SESSION['CMS']['lang'][$row['obj_key_project_id']];
            }

            $name=$this->getObjectName( $row['obj_id'], $lang_id, $prefix );
            $row=array_merge( $row, $name );

            $entry[0]['obj_id']=$row['obj_id'];
            $entry[0]['obj_name']=$row['obj_name_name'];
            $result=$this->getRecursivePath( $row['obj_parent_obj_id'] );
        }
        $this->ccdSQL->free_result( $res );
        $result=array_merge( $result, $entry );
        return $result;
    }
// -------------------------------------------------------------------------------------------------------------------

    function getRecursivePathID( $obj_id )
    {
        $result=array();
        $entry=array();
        $query=
            "SELECT obj_id,obj_parent_obj_id FROM obj_index WHERE obj_id = '" . $obj_id
            . "' AND obj_parent_obj_id <> 0";
        $res=$this->ccdSQL->query( $query );

        if ( $row=$this->ccdSQL->fetch_array( $res ) )
        {
            $entry[]=$row['obj_id'];
            $result=$this->getRecursivePathID( $row['obj_parent_obj_id'] );
        }
        $result=array_merge( $result, $entry );
        return $result;
    }


// -------------------------------------------------------------------------------------------------------------------
    function getRoot( $obj_id )
    {
        global $path_array;
        $path_array[]=$obj_id;
        $query=
            "SELECT obj_id,obj_parent_obj_id,class_name FROM obj_index left join classes ON obj_key_class_id=class_id WHERE obj_id='"
            . $obj_id . "'";
        $res=$this->ccdSQL->query( $query );
        $row=$this->ccdSQL->fetch_assoc( $res );

        if ( ( $row['class_name'] != "ROOT" ) AND ( $row['obj_parent_obj_id'] > 0 ) )
        {
            $return=$this->getRoot( $row['obj_parent_obj_id'] );
        }
        else
        {
            $return=$row['obj_id'];
        }
        return $return;
    }

// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------

    function getNaviTree( $root_id, $lastpages, $project_id=false )
    {
        $results=array();

        if ( $project_id != false )
        {
            $project_where=" AND obj_key_project_id='" . $project_id . "'";
        }
        else
        {
            $project_where="";
        }
        $query=
            "SELECT * FROM obj_index WHERE obj_parent_obj_id = '" . $root_id . "' AND obj_deleted=0 " . $project_where
            . " AND obj_no_structure=0 and obj_is_navi = 1 ORDER BY obj_position";
        $res=$this->ccdSQL->query( $query );

        while ( $row=$this->ccdSQL->fetch_array( $res ) )
        {

            $names=$this->getObjectName( $row['obj_id'], $_SESSION['CMS']['lang'][$project_id] );
            $row=array_merge( $row, $names );

            $results[]=array
                (
                "name" => $lastpages . $row['obj_name_name'],
                "value" => $row['obj_id'],
                "url" => "/" . $row['obj_id'] . "/" . $this->rewrite_name( $row['obj_name_name'] )
                );

            $tmp_array=$this->getNaviTree( $row['obj_id'], $lastpages . $row['obj_name_name'] . ">", $project_id );
            $results=array_merge( $results, $tmp_array );
        }
        return $results;
    }


// -------------------------------------------------------------------------------------------------------------------

    function getAlternativeObjName( $obj_id )
    {

        $query="SELECT * FROM obj_index 
							LEFT JOIN obj_names ON
								(obj_name_key_obj_id = obj_id AND obj_name_key_lang_id='" . MMCMS_DEFAULT_LANG . "') 
							WHERE obj_id='" . $obj_id . "'
							";
        $res=$this->ccdSQL->query( $query );

        if ( $row=$this->ccdSQL->fetch_assoc( $res ) )
        {
            return "[" . MMCMS_DEFAULT_LANG_CODE . "] " . $row['obj_name_name'];
        }
        else
        {
            return "undefined";
        }
    }

// -------------------------------------------------------------------------------------------------------------------

    function getObjectName( $obj_id, $lang_id, $prefix=false )
    {

        $obj=new ccdsObject( $obj_id );
        return $obj->getName( $lang_id, $prefix );
    }
// -------------------------------------------------------------------------------------------------------------------

    function CountObjects( $root_id, $deleted=0 )
    {

        $count=0;

        $query="SELECT obj_id FROM obj_index WHERE obj_parent_obj_id='" . $root_id . "' AND obj_deleted=" . $deleted;
        $res=$this->ccdSQL->query( $query );

        if ( $this->ccdSQL->num_rows( $res ) > 0 )
        {
            $count+=$this->ccdSQL->num_rows( $res );

            while ( $row=$this->ccdSQL->fetch_assoc( $res ) )
                $count+=$this->CountObjects( $row['obj_id'] );
        }

        return $count;
    }


// -------------------------------------------------------------------------------------------------------------------

    function get_file_extension( $file )
    {

        return strtolower( preg_replace( "@(.*)\.(.*?)$@", "$2", $file ) );
    }


// -------------------------------------------------------------------------------------------------------------------

    function get_file_type( $file )
    {

        $extension=$this->get_file_extension( $file );
        $type=false;

        foreach ( $this->file_types as $type => $extensions )
        {
            if ( in_array( $extension, $extensions ) )
                $filetype=$type;
        }

        if ( !$filetype )
            $filetype="other";

        return $filetype;
    }

// -------------------------------------------------------------------------------------------------------------------

    function get_file_icon( $file )
    {
        return $this->file_icons[$this->get_file_type( $file )];
    }
// -------------------------------------------------------------------------------------------------------------------

    function getFileDetails( $root_dir, $dir, $file )
    {

        $file_path=$root_dir . $dir . $file;

        if ( is_file( $file_path ) )
        {
            /*
                demo file object
                var detailViewData = {
                    id: 'item1',
                    name: 'Foto1.jpg',
                    resolution: '800x600',
                    size: "3 MB",
                    ctime: "22.01.98 8:30",
                    mtime: "22.01.98 22:00",
                    descr: "ich bins",
                    keywords: 'oleg boleg kof oleg008',
                    preview: 'Foto1.jpg'
                };
            */

            $stats=stat( $file_path );

            $filedetails=array
                (
                "id" => crc32( $file_path ),
                "name" => $file,
                "type" => $this->get_file_type( $file ),
                "size" => $this->getFileSize( $file_path ),
                "mtime" => date( "d.m.Y H:i", $stats['mtime'] ),
                "ctime" => date( "d.m.Y H:i", $stats['ctime'] )
                );

            if ( $filedetails['type'] == "image" )
            {
                $iCache=ccdsImageCache::getInstance();
                $return=$iCache->image_info( $file_path );

                $img_src=$iCache->img_cache_resize( $file_path, 380, 300, 0, 80 );
                $filedetails['preview']=$img_src['src'];
                $filedetails['resolution']=$return['width'] . "x" . $return['height'] . "px";
            }

            return $filedetails;
        }
        else
        {
            return false;
        }
    }

// -------------------------------------------------------------------------------------------------------------------

    function formatBytes( $bytes )
    {
        if ( $bytes >= ( 1024 * 1024 * 1024 ) )
        {
            $bytes=number_format( $filesize / ( 1024 * 1024 * 1024 ), 2 ) . " GB";
        }
        elseif ( $bytes >= ( 1024 * 1024 ) )
        {
            $bytes=number_format( $bytes / ( 1024 * 1024 ), 2 ) . " MB";
        }
        else
        {
            $bytes=number_format( $bytes / ( 1024 ), 2 ) . " kB";
        }

        return $bytes;
    }


// -------------------------------------------------------------------------------------------------------------------
    function getFileSize( $file )
    {

        $filesize=filesize( $file );

        return $this->formatBytes( $filesize );
    }

// -------------------------------------------------------------------------------------------------------------------

    function rewrite_filename( $mystring )
    {

        $tempstring=trim( $mystring );

        return $tempstring;
    }

    public function getRewriteFilename( $sString )
    {
        $sString=strtolower( htmlentities( $sString, ENT_NOQUOTES, "UTF-8" ) );
        $sString=str_replace( "&szlig;", "ss", $sString );
        $sString=preg_replace( "/&(.)(uml);/", "$1e", $sString );
        $sString=preg_replace( "/&(.)(acute|cedil|circ|ring|tilde|uml);/", "$1", $sString );
        $sString=preg_replace( "/([^a-z0-9\.]+)/", "-", html_entity_decode( $sString, ENT_NOQUOTES ) );
        $sString=trim( $sString, "-" );
        return $sString;
    }

    public function getRewriteString( $sString )
    {
        $string=strtolower( htmlentities( $sString, ENT_NOQUOTES, "UTF-8" ) );
        $string=str_replace( "&szlig;", "ss", $string );
        $string=preg_replace( "/&(.)(uml);/", "$1e", $string );
        $string=preg_replace( "/&(.)(acute|cedil|circ|ring|tilde|uml);/", "$1", $string );
        $string=preg_replace( "/([^a-z0-9]+)/", "-", html_entity_decode( $string, ENT_NOQUOTES, "UTF-8" ) );
        $string=trim( $string, "-" );
        return $string;
    }

    function rewrite_name( $mystring )
    {
        $tempstring=trim( $mystring );
        return $this->getRewriteString( $tempstring );
    }

// -------------------------------------------------------------------------------------------------------------------

    function full_copy( $source, $target )
    {
        if ( is_dir( $source ) )
        {
            @mkdir ($target);

            $d=dir( $source );

            while ( FALSE !== ( $entry=$d->read()) )
            {
                if ( $entry == '.' || $entry == '..' )
                {
                    continue;
                }

                $Entry=$source . '/' . $entry;

                if ( is_dir( $Entry ) )
                {
                    $this->full_copy( $Entry, $target . '/' . $entry );
                    continue;
                }
                copy( $Entry, $target . '/' . $entry );
            }

            $d->close();
        }
        else
        {
            copy( $source, $target );
        }
    }

    function strip( $string )
    {

        $string=str_replace( "\n", " ", $string );
        $string=str_replace( "\r", " ", $string );
        $string=str_replace( "\t", " ", $string );
        return $string;
    }


// -------------------------------------------------------------------------------------------------------------------
    function getFileListing( $root_dir, $read_dir, $filetype="ALL" )
    {

        $previous_dir=array();
        $search_dir=$root_dir . $read_dir;

        if ( !is_dir( $search_dir ) )
            return array();

        $archiveDir=opendir( $search_dir );
        $fileArray=array();

        while ( false !== ( $archiveFile=readdir( $archiveDir )) )
        {
            $fileArray[]=$archiveFile;
        }
        closedir ($archiveDir);

        $fileCount=count( $fileArray );
        $count_found=0;
        $count_lost=0;
        $ycount=0;
        $xcount=0;
        $files=array();
        $directories=array();

        for ( $arrayPosition=0; $arrayPosition < $fileCount; $arrayPosition++ )
        {
            if ( ( $fileArray[$arrayPosition] != "." ) AND ( $fileArray[$arrayPosition] != ".." ) )
            {
                if ( is_dir( $search_dir . $fileArray[$arrayPosition] ) )
                {
                    $directories[]=$fileArray[$arrayPosition];
                }
                elseif ( $fileArray[$arrayPosition] != "" )
                {
                    $tmp_name=$this->rewrite_filename( $fileArray[$arrayPosition] );

                    if ( $filetype == "ALL" )
                    {
                        $files[]=$fileArray[$arrayPosition];
                    }
                    elseif ( ( $this->get_file_type( $fileArray[$arrayPosition] )
                        == $filetype ) OR ( $fileArray[$arrayPosition] == ".." ) )
                    {
                        $files[]=$fileArray[$arrayPosition];
                    }
                }
            }
        }

        natcasesort ($files);
        natcasesort ($directories);

        foreach ( $directories as $key => $dir )
        {
            $directories[$key]=array
                (
                "id" => crc32( $search_dir . $dir ),
                "type" => "folder",
                "name" => $dir,
                "path" => $read_dir
                );
        }

        if ( $filetype == "*dir*" )
            return $directories;

        foreach ( $files as $key => $file )
        {
            if ( $filetype == "ALL" )
            {
                $files[$key]=array
                    (
                    "id" => crc32( $search_dir . $file ),
                    "end" => $this->get_file_extension( $file ),
                    "name" => $file,
                    "type" => $this->get_file_type( $file ),
                    "icon" => $this->get_file_icon( $file ),
                    "size" => $this->getFileSize( $search_dir . $file ),
                    "path" => $read_dir
                    );
            }
            elseif ( $filetype == $this->get_file_type( $file ) )
            {
                $files[$key]=array
                    (
                    "id" => crc32( $search_dir . $file ),
                    "end" => $this->get_file_extension( $file ),
                    "type" => $this->get_file_type( $file ),
                    "name" => $file,
                    "icon" => $this->get_file_icon( $file ),
                    "size" => $this->getFileSize( $search_dir . $file ),
                    "path" => $read_dir
                    );
            }
        }

        return array_merge( $previous_dir, $directories, $files );
    }
// -------------------------------------------------------------------------------------------------------------------

    function GetBytesRead( $tmp_dir )
    {
        $bytesRead=0;

        if ( is_dir( $tmp_dir ) )
        {
            if ( $handle=opendir( $tmp_dir ) )
            {
                while ( false !== ( $file=readdir( $handle )) )
                {
                    if ( $file != '.' && $file != '..' && $file != 'flength' )
                    {
                        $bytesRead+=filesize( $tmp_dir . "/" . $file );
                    }
                }
                closedir ($handle);
            }
        }

        $bytesRead=trim( $bytesRead );

        return $bytesRead;
    }


//****************************************************************************************************************************

    function serialize_name( $name, $obj_parent_obj_id, $obj_name_key_lang_id, $obj_id )
    {
        $i=1;
        $obj_name_is_unique=false;
        $obj_serialized_name=$this->rewrite_name( $name );
        $obj_new_name=$obj_serialized_name;

        while ( !$obj_name_is_unique )
        {
            $query="SELECT * 
								FROM obj_names 
										LEFT JOIN
											obj_index ON obj_name_key_obj_id = obj_id
					
									 WHERE 1
									 AND obj_name_serialized='" . $obj_new_name . "'
									 AND obj_parent_obj_id='" . $obj_parent_obj_id . "'
									 AND obj_name_key_lang_id='" . $obj_name_key_lang_id . "'
									 AND obj_name_key_obj_id <> '" . $obj_id . "'
									 ";

            $res2=$this->ccdSQL->query( $query );

            if ( $row2=$this->ccdSQL->fetch_assoc( $res2 ) )
            {
                $obj_new_name=$obj_serialized_name . $i;
            }
            else
            {
                $obj_serialized_name=$obj_new_name;
                $obj_name_is_unique=true;
            }
            $i++;
        }
        return $obj_serialized_name;
    }

//****************************************************************************************************************************

    function serialize_all_names( )
    {
        $this->ccdSQL->query( "UPDATE obj_names SET obj_name_serialized =''" );

        $query="SELECT * FROM obj_index 
							LEFT JOIN obj_names ON obj_name_key_obj_id = obj_id
		
						ORDER BY obj_parent_obj_id,obj_position";

        $res=$this->ccdSQL->query( $query );
        //print $this->ccdSQL->error();

        while ( $row=$this->ccdSQL->fetch_assoc( $res ) )
        {
            $obj_serialized_name=
                serialize_name( $row['obj_name_name'], $row['obj_parent_obj_id'], $row['obj_name_key_lang_id'],
                    $row['obj_id'] );
            print $obj_serialized_name;
            $this->ccdSQL->query( "UPDATE obj_names SET obj_name_serialized ='" . $obj_serialized_name
                . "' WHERE obj_name_id='" . $row['obj_name_id'] . "'" );
        }

        print "<br />";
    }

    function load_plugin_frontend_function( $obj_id, $obj_content )
    {

        $return=array();
        $query="SELECT * FROM obj_index 
							LEFT JOIN classes ON
								obj_key_class_id = class_id
							LEFT JOIN extensions ON
								class_key_ext_id = ext_id	
							LEFT JOIN projects ON
							ext_key_project_id = project_id
							
							
							WHERE obj_id = '"
            . $obj_id . "'";
        $res=$this->ccdSQL->query( $query );

        if ( $obj=$this->ccdSQL->fetch_assoc( $res ) )
        {
            if ( $obj['obj_link_obj_id'] > 0 )
            {
                $query="SELECT * FROM obj_index 
										LEFT JOIN classes ON
											obj_key_class_id = class_id
										LEFT JOIN extensions ON
											class_key_ext_id = ext_id	
										LEFT JOIN projects ON
										ext_key_project_id = project_id
										WHERE obj_id = '"
                    . $obj['obj_link_obj_id'] . "'";
                $res=$this->ccdSQL->query( $query );
                $obj=$this->ccdSQL->fetch_assoc( $res );
            }

            $ext_file=
                $this->config->get( 'EXTENSION_DIR' ) . $obj['project_dir'] . "/" . $obj['ext_dir'] . "/"
                . $obj['class_dir'] . "/frontend/" . $obj['class_name'] . ".inc.php";

            if ( file_exists( $ext_file ) )
            {
                include_once ($ext_file);
                $ext_func="mmccds_" . $obj['class_name'];

                if ( function_exists( $ext_func ) )
                {
                    $return=$ext_func( $obj_id, $page_language_id, $obj_content );
                }
            }
        }
        return $return;
    }

    function MarkObjectDeleted( $obj_id, $recursive=false, $deleted=1 )
    {
        @$this->ccdSQL->query( "UPDATE obj_index SET obj_deleted=" . $deleted . " WHERE obj_id='" . $obj_id . "'" );

        if ( $recursive )
        {
            $query="SELECT * FROM obj_index WHERE obj_parent_obj_id='" . $obj_id . "'";

            $res=$this->ccdSQL->query( $query );

            while ( $row=$this->ccdSQL->fetch_assoc( $res ) )
                $this->MarkObjectDeleted( $row['obj_id'], true, $deleted );
        }
        return true;
    }

// ************************************************************************************************************************

    function ObjectDelete( $obj_id )
    {

        $object=new ccdsObject( $obj_id );

        if ( $object->hasContent() )
        {
            $query="SELECT * FROM obj_versions WHERE obj_vers_key_obj_id='" . $obj_id . "'";
            $res=$this->ccdSQL->query( $query );

            while ( $vers=$this->ccdSQL->fetch_assoc( $res ) )
            {
                $query=
                    "DELETE FROM " . $object->getTable() . " WHERE " . $object->__getIDfield() . "='"
                    . $vers['obj_vers_id'] . "'";
                $this->ccdSQL->query( $query );
            }
            $this->ccdSQL->query( "DELETE FROM obj_versions WHERE obj_vers_key_obj_id='" . $obj_id . "'" );
        }
        $this->ccdSQL->query( "DELETE FROM obj_names WHERE obj_name_key_obj_id='" . $obj_id . "'" );

        $this->ccdSQL->query( "DELETE FROM obj_index WHERE obj_id='" . $obj_id . "'" );

        $query="SELECT * FROM obj_index WHERE obj_parent_obj_id='" . $obj_id . "'";
        $res=$this->ccdSQL->query( $query );

        while ( $row=$this->ccdSQL->fetch_assoc( $res ) )
        {
            $this->ObjectDelete( $row['obj_id'] );
        }
    }


//****************************************************************************************************************************
    function is_in_tree( $obj_id )
    {
        global $page_path;

        if ( in_array( $obj_id, $page_path ) )
        {
            return true;
        }
        else
        {
            return false;
        }
    }
//****************************************************************************************************************************

    function has_elements( $obj_id, $lang )
    {

        $count=0;

        $query="
		SELECT COUNT(obj_id) as anzahl FROM obj_index 

		STRAIGHT_JOIN obj_index_public as objp1  ON (
			objp1.objp_key_obj_id = obj_id
			AND
			objp1.objp_key_lang_id = '" . $lang . "'
		)
		WHERE 
		obj_deleted = 0 and obj_parent_obj_id='" . $obj_id . "'
				AND (
					(obj_expire=0) 
						OR  (
							obj_expire=1 
							AND obj_expire_start <= '" . time() . "'
							AND obj_expire_end >= '" . time() . "'
						)
				)
	
	";

        $res=$this->ccdSQL->query( $query );
        $row=$this->ccdSQL->fetch_assoc( $res );

        if ( $row['anzahl'] > 0 )
        {
            return true;
        }
        else
        {
            return false;
        }
    }

// -------------------------------------------------------------------------------------------------------------------

    function is_in_tree_recursive( $obj_id, $destination )
    {

        $path=$this->getRecursivePath( $destination );
        $is_in_tree=false;

        foreach ( $path as $obj )
        {
            if ( $obj['obj_id'] == $obj_id )
                $is_in_tree=true;
        }
        return $is_in_tree;
    }
// -------------------------------------------------------------------------------------------------------------------

    function smarty_htmlentitiesutf8( $params )
    {
        return htmlentities( $params, ENT_QUOTES, "UTF-8" );
    }
// -------------------------------------------------------------------------------------------------------------------

    function getPermissionsClass2Class( $class_id )
    {

        $permissions=array();
        $query="SELECT * FROM permissions_class_2_class WHERE class_2_class_node_id = '" . $class_id . "'";
        $res=$this->ccdSQL->query( $query );

        while ( $row=$this->ccdSQL->fetch_assoc( $res ) )
        {
            $permissions[$row['class_2_class_child_id']]=array
                (
                "allow" => 1,
                "visible" => $row['class_2_class_visible']
                );
        }

        return $permissions;
    }
// -------------------------------------------------------------------------------------------------------------------

    function copy_object( $obj_id, $dest_obj_id, $user_id, $recursive=false )
    {

        $query="SELECT * FROM obj_index WHERE obj_id='" . addslashes( $obj_id ) . "'";
        $res=$this->ccdSQL->query( $query );
        $obj=$this->ccdSQL->fetch_assoc( $res );

        $query=
            "SELECT MAX(obj_position) as pos FROM obj_index WHERE obj_parent_obj_id='" . addslashes( $dest_obj_id )
            . "'";
        $res=$this->ccdSQL->query( $query );
        $pos=$this->ccdSQL->fetch_assoc( $res );

        $query=" INSERT INTO
                `obj_index`
                (
                `obj_parent_obj_id`,
                `obj_position`,
                `obj_attributes`,
                `obj_key_tpl_id`,
                `obj_created`,
                `obj_created_key_user_id`,
                `obj_last_edit`,
                `obj_last_edit_key_user_id`,
                `obj_cacheable`,
                `obj_is_navi`,
                `obj_key_class_id`,
                `obj_key_project_id`
                ) VALUES (
                '" . addslashes( $dest_obj_id ) . "',
                '" . ( $pos['pos'] + 1 ) . "',
                '" . $obj['obj_attributes'] . "',
                '" . $obj['obj_key_tpl_id'] . "',
                '" . $obj['obj_created'] . "',
                '" . $obj['obj_last_edit_key_user_id'] . "',
                '" . time() . "',
                '" . $user_id . "',
                '" . $obj['obj_cacheable'] . "',
                '" . $obj['obj_is_navi'] . "',
                '" . $obj['obj_key_class_id'] . "',
                '" . $obj['obj_key_project_id'] . "'
                )
                ";

        $res=$this->ccdSQL->query( $query );
        $error=$this->ccdSQL->error();

        if ( $error == "" )
        {
            $new_obj_id=$this->ccdSQL->insert_id();
            $query="SELECT * FROM obj_names WHERE obj_name_key_obj_id='" . $obj['obj_id'] . "'";
            $res=$this->ccdSQL->query( $query );

            while ( $row=$this->ccdSQL->fetch_assoc( $res ) )
            {
                if ( $dest_obj_id == $obj['obj_parent_obj_id'] )
                    $row['obj_name_name'] . " Kopie";
                $this->ccdSQL->query( "INSERT INTO obj_names
                             (
                             obj_name_key_lang_id,
                             obj_name_key_obj_id,
                             obj_name_name,
                             obj_name_serialized
                             )
                             VALUES (
                             '" . $row['obj_name_key_lang_id'] . "',
                             '" . $new_obj_id . "',
                             '" . $row['obj_name_name'] . "',
                             '" . $this->serialize_name( $row['obj_name_name'], $aFormValues['obj_id'], $row['obj_name_key_lang_id'], $new_obj_id ) . "'
                             )
                             " );
            }
            $class=new ccdsObject( $obj['obj_id'] );

            if ( $class->hasContent() )
            {
                $query="SELECT * FROM languages";
                $res=$this->ccdSQL->query( $query );

                while ( $lang=$this->ccdSQL->fetch_assoc( $res ) )
                {
                    $query=
                        "SELECT * FROM obj_versions WHERE obj_vers_key_obj_id='" . $obj_id
                        . "' AND obj_vers_key_lang_id='" . $lang['lang_id']
                        . "' ORDER BY obj_vers_visible desc LIMIT 1";
                    $res2=$this->ccdSQL->query( $query );
                    $obj_vers=$this->ccdSQL->fetch_assoc( $res2 );

                    $query="INSERT INTO
                             `obj_versions`
                             (
                             `obj_vers_key_obj_id`,
                             `obj_vers_created`,
                             `obj_vers_creator`,
                             `obj_vers_visible`,
                             `obj_vers_key_lang_id`
                             )
                             VALUES
                             (
                             '" . $new_obj_id . "',
                             '" . time() . "',
                             '" . $user_id . "',
                             '" . $obj_vers['obj_vers_visible'] . "',
                             '" . $obj_vers['obj_vers_key_lang_id'] . "'
                             )";
                    $this->ccdSQL->query( $query );
                    $vers_id=$this->ccdSQL->insert_id();

                    $query="SELECT * FROM pictures WHERE picture_key_obj_id='" . $obj_vers['obj_vers_id'] . "'";
                    $pic_res=$this->ccdSQL->query( $query );

                    while ( $pic=$this->ccdSQL->fetch_assoc( $pic_res ) )
                    {

                        $this->ccdSQL->query( "INSERT INTO pictures
                                     (
                                     picture_filename,
                                     picture_description,
                                     picture_key_obj_id,
                                     picture_key_fieldname,
                                     picture_dir
                                     )
                                     VALUES (
                                     '" . $pic['picture_filename'] . "',
                                     '" . $pic['picture_description'] . "',
                                     '" . $vers_id . "',
                                     '" . $pic['picture_key_fieldname'] . "',
                                     '" . $pic['picture_dir'] . "'

                                     )
                                     " );
                    }

                    $content=$class->__getVersionRow( $obj_vers['obj_vers_id'] );

                    if ( is_array( $content ) )
                    {
                        $seperator="";
                        $fields="";
                        $values="";

                        foreach ( $content as $key => $value )
                        {
                            if ( $key != $class->__getIDfield() )
                            {
                                $fields.=$seperator . $key;
                                $values.=$seperator . "'" . $value . "' ";
                                $seperator=", ";
                            }
                            else
                            {
                                $fields.=$seperator . $key;
                                $values.=$seperator . "'" . $vers_id . "' ";
                                $seperator=", ";
                            }
                        }
                        $this->ccdSQL->query( "INSERT INTO " . $class->getTable() . " (" . $fields . ") VALUES ("
                            . $values . ")" );
                    }
                }
            }
        }
        else {
        //debugMessage($objResponse,"FEHLER: ".$error);
        }

        if ( $recursive )
        {
            $query="SELECT * FROM obj_index WHERE obj_parent_obj_id='" . $obj_id . "'";
            $res=$this->ccdSQL->query( $query );

            while ( $row=$this->ccdSQL->fetch_assoc( $res ) )
                $this->copy_object( $row['obj_id'], $new_obj_id, $user, $recursive );
        }
        return $new_obj_id;
    }

// -------------------------------------------------------------------------------------------------------------------

}
// -------------------------------------------------------------------------------------------------------------------

